package com.clouddisk.file.chain.impl;

import com.clouddisk.common.exception.BusinessException;
import com.clouddisk.file.chain.FileOperationHandler;
import com.clouddisk.file.chain.FileOperationContext;
import com.clouddisk.file.service.FileService;
import com.clouddisk.user.feign.UserFeignClient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class StorageCheckHandler implements FileOperationHandler {

    private final FileService fileService;
    private final UserFeignClient userFeignClient;
    private FileOperationHandler next;

    @Override
    public void handle(FileOperationContext context) {
        if (!context.isShouldContinue()) {
            return;
        }

        // 检查用户存储空间是否足够
        Long fileSize = context.getUploadDTO().getFile().getSize();
        Long storageUsed = fileService.getUserStorageUsed(context.getUserId());
        Long storageLimit = userFeignClient.getUserStorageLimit(context.getUserId());
        
        if (storageUsed + fileSize > storageLimit) {
            throw new BusinessException("存储空间不足");
        }

        if (next != null) {
            next.handle(context);
        }
    }

    @Override
    public void setNext(FileOperationHandler next) {
        this.next = next;
    }
} 